package com.houdoudou.customer.buy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Branch;
import com.houdoudou.bean.Car;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.bean.Product;
import com.houdoudou.bean.Sort;
import com.houdoudou.bean.Supplier;
import com.houdoudou.customer.R;
import com.houdoudou.customer.buy.FrgProductDetail.SavedBranchListAdapter;
import com.houdoudou.customer.buy.FrgProductDetail.SavedBranchListAdapter.Zujian;
import com.houdoudou.customer.common.AsynImageLoader;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.HorizontalListView;
import com.houdoudou.customer.common.SerializableJSONObject;
import com.houdoudou.customer.common.SerializableMap;
import com.houdoudou.customer.common.TimeUtil;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.sqlite.CarDao;
import com.houdoudou.customer.sqlite.CarManagement;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShopAct extends FragmentActivity{
	

	public static FragmentManager myFragmentMan ;
	public static Fragment frg_addtopackege;
	TextView pull_result,announcement;
	ImageButton back;
	ProgressBar progres;
	ExpandableListView listview_product;
	Button placeOrder;
	TextView  shopName;
	AsynImageLoader imageloader;
	MyExpandableListAdapter myListAdapter;	
	View.OnClickListener myOnclickListener;
	// List<Map<String,Object>> list_data_products=new ArrayList<Map<String,Object>>();
	JSONArray ja_index_product= new JSONArray();
	 JSONObject carJO=new JSONObject();
    public static JSONObject supplierJO;
	public static String Supplier_Telnum,Owner_Telnum,Arrive_Time;
	public static int Minute_NoOrder;
    public static String  Machine_Name="";
	public static String  Machine_Address="",Major_Business;
	public static String  welcomewords,addresswords,timewords, noticewords,servicewords;
	boolean isBeyongMoneyMini=false;
	
	/*显示购物车所需控件*/
	 LinearLayout lt_showsaved,branches_saved;
      LinearLayout lt_shadow;
      ListView listview_showsaved;
	TextView branch_incar,clear_saved;
	
	JSONArray Saved_Branch_JA=new JSONArray();
	 boolean isShowSaved=false;
	 SavedBranchListAdapter savedListAdapter;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_shop);
	  // init_data_test();
		Bundle bundle=getIntent().getExtras();
		System.out.println("bundle.containsKey(supplier);"+bundle.containsKey("supplier"));
		String temp =bundle.getString("supplier");
		supplierJO =JSONObject.fromObject(temp);
		System.out.print(supplierJO.toString());
		ja_index_product=supplierJO.getJSONArray("sorts");
		/*--------传递来的一些公共产生，在ProductAct里也需要用，--------*/
		Supplier_Telnum=supplierJO.getString(Supplier.TELNUM);
		Owner_Telnum=supplierJO.getString(Supplier.OWNER);
		Arrive_Time=supplierJO.getString("timeAA");
		Minute_NoOrder=supplierJO.getInt(Supplier.MINUTEMINI);
		 Machine_Name= Constant.machineJO.getString(Machine.NAME);
		 Machine_Address=Constant.machineJO.getString(Machine.ADDRESS);
		 Major_Business=supplierJO.getString(Supplier.MAJOR);
		 
		    carJO.put(Car.MACHINE, Constant.machineJO.getInt(Machine.ID));
			carJO.put(Car.TIMEFLAG, supplierJO.getInt(Car.TIMEFLAG));
			carJO.put(Car.SUPPLIER, supplierJO.getString(Supplier.TELNUM));
			
			
		myFragmentMan = getSupportFragmentManager();
		frg_addtopackege= new FrgProductDetail();
		
		imageloader= new AsynImageLoader(this);
		
		spell_announcement();
		init_listener();
		init_component();
		savedListAdapter= new SavedBranchListAdapter(ShopAct.this);
	    listview_showsaved.setAdapter(savedListAdapter);
	   
		
	  //  pull_product(shopInfo);
	}
	
	private void init_listener(){
		
			myOnclickListener= new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					
					if(v==back){
						new Thread () { 
							public void run () { 
							try { 
								
							Instrumentation inst= new Instrumentation(); 
							inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
							} catch(Exception e) { 
							e.printStackTrace(); 
							} 
							} 
							}.start();
                      }
					if(v==branches_saved){
						
						if(isShowSaved){
							hide_lt_saved();
						}else{
							lt_showsaved.setVisibility(View.VISIBLE);
							lt_shadow.setVisibility(View.VISIBLE);
							isShowSaved=true;
							placeOrder.setClickable(false);
						 }
						 }
						if(v==lt_shadow){
							if(isShowSaved){
								hide_lt_saved();
							}
						}
					  if(v==clear_saved){
						  if(Saved_Branch_JA.size()>0){
						//  new CarManagement(getActivity()).deleteOneProduct(Saved_Branch_JA.getJSONObject(0));
							  new CarDao(ShopAct.this).deleteOneSupplier(carJO); 
						  refresh_saved();
						  }
					  }	
					if(v==placeOrder){
						if(Saved_Branch_JA.size()==0){
						Toast.makeText(ShopAct.this, "请先选择商品", Toast.LENGTH_SHORT).show();
						return;
						}
						if(!isBeyongMoneyMini){
							Toast.makeText(ShopAct.this, "最小起订金额"+supplierJO.getDouble(Supplier.MONEYMINI), Toast.LENGTH_SHORT).show();
							return;	
						}
						
						//构造订单数据。
						JSONObject orderJO= Order.createBasicOrderJO(supplierJO);
						
					   // 构造订单产品表需要的数据。并统计订单价格等值。
							JSONArray orderProducts= new JSONArray();
							int productNum=0; //产品数量
							int volume=0; //总体积
							int boxNum=0; //箱格数量		
							double moneyProduct=0; //商品金额
							double moneyFreight=0; //运费。
						
							for(int i=0;i<Saved_Branch_JA.size();i++){
								System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^i="+i+"^^^^^^^^^^^^^^^^");
								JSONObject currentCarJO=Saved_Branch_JA.getJSONObject(i);			
									JSONObject orderProductJO= new JSONObject();
									orderProductJO.put(OrderProduct.PRODUCTID, currentCarJO.getInt(Car.PRODUCT));
									orderProductJO.put(OrderProduct.PRODUCTNAME, currentCarJO.getString(OrderProduct.PRODUCTNAME));
									orderProductJO.put(OrderProduct.PRODUCTTYPE,currentCarJO.getInt(OrderProduct.PRODUCTTYPE));
									orderProductJO.put(OrderProduct.BRANCHID, currentCarJO.getInt(Car.BRANCH));
									orderProductJO.put(OrderProduct.BRANCHNAME, currentCarJO.getString(OrderProduct.BRANCHNAME));
									orderProductJO.put(OrderProduct.BRANCHVOLUME, currentCarJO.getInt(OrderProduct.BRANCHVOLUME));
									orderProductJO.put(OrderProduct.BRANCHPRICE,currentCarJO.getDouble(OrderProduct.BRANCHPRICE));
									orderProductJO.put(OrderProduct.BRANCHNUM,currentCarJO.getInt(Car.NUMBER));
									orderProductJO.put(OrderProduct.BRANCHNUM,currentCarJO.getString(Car.NUMBER));		
								    orderProductJO.put(OrderProduct.DIR,currentCarJO.getString(OrderProduct.DIR));
									volume+=currentCarJO.getInt(OrderProduct.BRANCHVOLUME)*currentCarJO.getInt(Car.NUMBER);
									productNum+=currentCarJO.getInt(Car.NUMBER);
									moneyProduct+=currentCarJO.getDouble(OrderProduct.BRANCHPRICE)*currentCarJO.getInt(Car.NUMBER);
								 orderProducts.add(orderProductJO);
							
							}
							if(orderProducts.size()<=0){
								CommonFunction.alert(ShopAct.this, "无法提交", "请先选择产品"); return;
							}
							//
							orderJO.put("products", orderProducts);
							//产品汇总字段
							orderJO.put(Order.MONEYPRODUCT, moneyProduct);
							orderJO.put(Order.PRODUCTNUM, productNum);
							orderJO.put(Order.VOLUME, volume);
							boxNum= volume/orderJO.getInt(Order.BOXVOLUME)+1; 
							orderJO.put(Order.BOXNUM, boxNum);
							moneyFreight=boxNum*orderJO.getDouble(Order.BOXFEECU);
							orderJO.put(Order.MONEYFREIGHT, moneyFreight);
							orderJO.put(Order.MONEYCU, moneyFreight+moneyProduct);			
							Intent intent= new Intent(ShopAct.this, PlaceOrderAct.class);
							intent.putExtra("orderJO", orderJO.toString());				
							startActivity(intent);		
					}
					
					
				               }// onClick			
			                      };					
		      }
	
	private void init_component(){
		
		
	
		progres= (ProgressBar)findViewById(R.id.prgs_act_shop);
		listview_product=  (ExpandableListView)findViewById(R.id.list_act_shop);
		pull_result= (TextView) findViewById(R.id.pullresult_act_shop);
		announcement= (TextView) findViewById(R.id.tv_announcement_act_shop);
		back= (ImageButton) findViewById(R.id.back_act_shop);
		lt_shadow=(LinearLayout) findViewById(R.id.lt_shadow_act_shop);
		lt_showsaved=(LinearLayout) findViewById(R.id.lt_showsaved_act_shop);
		branches_saved=(LinearLayout) findViewById(R.id.lt_saved_act_shop);
		clear_saved=(TextView) findViewById(R.id.tv_clear_showsavedtitle_act_shop);
		branch_incar=(TextView) findViewById(R.id.tv_incar_act_shop);
		listview_showsaved=(ListView) findViewById(R.id.listview_showsaved_act_shop);
		placeOrder=(Button) findViewById(R.id.btn_placeorder_act_shop);
		shopName= (TextView) findViewById(R.id.tv_shopname_act_shop);
		
	    back.setOnClickListener(myOnclickListener);
	    clear_saved.setOnClickListener(myOnclickListener);
	    branches_saved.setOnClickListener(myOnclickListener);
	    lt_shadow.setOnClickListener(myOnclickListener);
	    placeOrder.setOnClickListener(myOnclickListener);
		/*---------------------------------------*/
		myListAdapter= new MyExpandableListAdapter(this);	
		listview_product.setAdapter(myListAdapter);		
		listview_product.setOnChildClickListener(new ExpandableListView.OnChildClickListener(){
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				JSONObject 	Current_Product_JSON=ja_index_product.getJSONObject(groupPosition).getJSONArray("products").getJSONObject(childPosition);
			
				Intent  intent= new Intent(ShopAct.this,ProductAct.class);
			 
				intent.putExtra("product", Current_Product_JSON.toString());
				startActivity(intent);
				 	//startActivityForResult(intent, 1);			 
				return false;
			}
			
		});
		myListAdapter.notifyDataSetChanged();
		
		
		
		/*---------------------------------------*/
		
		announcement.setText(welcomewords+addresswords+timewords+noticewords+servicewords);
	
		
		progres.setVisibility(View.GONE);
		pull_result.setVisibility(View.GONE);
	    lt_shadow.setVisibility(View.GONE);
		lt_showsaved.setVisibility(View.GONE);
		listview_product.setVisibility(View.VISIBLE);
		
		shopName.setText(supplierJO.getString(Supplier.NAME));
	}
	public  void hide_lt_saved(){
		lt_showsaved.setVisibility(View.GONE);
		lt_shadow.setVisibility(View.GONE);
		isShowSaved=false;
		placeOrder.setClickable(true);
	}
	private void spell_announcement(){

		String[] timeparse= new String[2];
		timeparse[0]=Arrive_Time.substring(0, 2);
		timeparse[1]=Arrive_Time.substring(2, 4);
		int timeleft = 0;
		String timelatest = "";
		try{
		int hourtoarrive=Integer.parseInt(timeparse[0]);
		int minutetoarrive=Integer.parseInt(timeparse[1]);
		
		 int hourlatest,minutelatest;
		 hourlatest=(hourtoarrive*60+minutetoarrive-Minute_NoOrder)/60;
		 minutelatest=(hourtoarrive*60+minutetoarrive-Minute_NoOrder)%60;
		 if(hourlatest<10){ timelatest="0"+hourlatest+":";
		   }else{ timelatest=hourlatest+":"; }
		 if(minutelatest<10){timelatest+="0"+minutelatest; 
		   }else{timelatest+=minutelatest; }
		 
		 timeleft=hourtoarrive*60+minutetoarrive-TimeUtil.getCurrentMinute();
				}catch(Exception e){
					e.printStackTrace();
				}
		 welcomewords="    欢迎光临！ 本店主营"+Major_Business+"。";
		 addresswords="送达地址："+Machine_Address+Machine_Name+"。";
		 timewords="送达时间："+Arrive_Time+"。最迟下单时间："+timelatest+"。";
		 timewords+="最小起订金额："+ supplierJO.getDouble(Supplier.MONEYMINI)+"。";
		 noticewords="";
		if(timeleft>0&&timeleft<59){
			noticewords+="如需今日送达,下单时间还剩"+timeleft+"分钟";
		}else if(timeleft<=0){
			noticewords+="已过今日送达的最迟下单时间，可预定明天订单。";
		  }
		servicewords="服务电话："+supplierJO.getString(Supplier.SERVICETELNUM)+"。";
	}
	
	

	
	class MyExpandableListAdapter extends BaseExpandableListAdapter {
		 
		  private Context context;
		 
		  public MyExpandableListAdapter(Context context) {
		   this.context = context;
		  }
		  
		  class GroupHolder {
			  public TextView indexname,number;
			  public ImageView img;
			 }
			 
			 class ItemHolder {
			  public ImageView productPic;
			  public TextView productName,unitPrice,saleNum,selectedNum;
			 }
		  @Override
		  public int getGroupCount() {
		 //  return list_data_products.size();
			  return ja_index_product.size();
		  }
		 
		  @Override
		  public int getChildrenCount(int groupPosition) {
		  
			//List<Map<String,Object>>Products= (List<Map<String, Object>>) list_data_products.get(groupPosition).get("Products");
			   JSONArray Products=ja_index_product.getJSONObject(groupPosition).getJSONArray("products");
			return Products.size();
		       
		  }
		 
		  @Override
		  public Object getGroup(int groupPosition) {
		   return ja_index_product.getJSONObject(groupPosition);
		  }
		 
		  @Override
		  public Object getChild(int groupPosition, int childPosition) {
			  JSONArray Products=ja_index_product.getJSONObject(groupPosition).getJSONArray("products");
		   return Products.getJSONObject(childPosition);
		  }
		 
		  @Override
		  public long getGroupId(int groupPosition) {
		   return groupPosition;
		  }
		 
		  @Override
		  public long getChildId(int groupPosition, int childPosition) {
		   return childPosition;
		  }
		 
		  @Override
		  public boolean hasStableIds() {
		   return true;
		  }
		 
		  @Override
		  public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		
			  GroupHolder groupHolder = null;
		           if (convertView == null) {
		                              convertView = (View) getLayoutInflater().from(context).inflate( R.layout.list_parent_act_shop, null);
		                              groupHolder = new GroupHolder();
		                              groupHolder.indexname = (TextView) convertView.findViewById(R.id.tv_indexname_list_parent_shopact);
		                              groupHolder.number = (TextView) convertView.findViewById(R.id.tv_number_list_parent_shopact);
		                              convertView.setTag(groupHolder);
		                } else {
		                    groupHolder = (GroupHolder) convertView.getTag();
		                                      }
		           groupHolder.indexname.setText(ja_index_product.getJSONObject(groupPosition).getString(Sort.NAME));
		           int Selected_Num_Index=ja_index_product.getJSONObject(groupPosition).getInt("Selected_Num_InIndex");
		           groupHolder.number.setText(String.valueOf(Selected_Num_Index));
		           if(Selected_Num_Index<=0){ groupHolder.number.setVisibility(View.INVISIBLE);
		           }else{ groupHolder.number.setVisibility(View.VISIBLE);}
		           
		                //     groupHolder.txt.setText(list_data_products.get(groupPosition).toString());
		                             return convertView;
		     }
		 
		  @Override
		  public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
		   ItemHolder itemHolder = null;
		   if (convertView == null) {
		                convertView = (View) getLayoutInflater().from(context).inflate (R.layout.list_child_act_shop, null);
		                itemHolder = new ItemHolder();
		                 itemHolder.productName = (TextView) convertView.findViewById(R.id.tv_productname_list_child_shopact);
		                 itemHolder.productPic = (ImageView) convertView.findViewById(R.id.img_list_child_shopact);
		                 itemHolder.unitPrice=(TextView) convertView.findViewById(R.id.tv_price_list_child_shopact); 
		                 itemHolder.saleNum=(TextView) convertView.findViewById(R.id.tv_salenum_list_child_shopact);
		                 itemHolder.selectedNum=(TextView) convertView.findViewById(R.id.tv_selectedNum_list_child_shopact);
		                  convertView.setTag(itemHolder);
		   } else {
		    itemHolder = (ItemHolder) convertView.getTag();
		   }
		   JSONObject product= ja_index_product.getJSONObject(groupPosition).getJSONArray("products").getJSONObject(childPosition);
		   itemHolder.productName.setText(product.getString(Product.NAME));
		   itemHolder.saleNum.setText("销量："+String.valueOf(product.getInt(Product.SALE)));
		   double temp_price=product.getJSONArray("branches").getJSONObject(0).getDouble(Branch.PRICE);
		   itemHolder.unitPrice.setText("￥"+String.valueOf(temp_price));
		   int Selected_Num_Product= product.getInt("Selected_Num_InProduct");
		   itemHolder.selectedNum.setText(String.valueOf(Selected_Num_Product));
		   if(Selected_Num_Product<=0){
			   itemHolder.selectedNum.setVisibility(View.INVISIBLE);
		   }else{
			   itemHolder.selectedNum.setVisibility(View.VISIBLE);
		   }
		   String url=product.getString(Product.DIR)+"0.jpg";
               imageloader.showImageAsyn(itemHolder.productPic, url, R.drawable.machine_list);
		//   itemHolder.txt.setText(item_list.get(groupPosition).get( childPosition));
		 //  itemHolder.img.setBackgroundResource(item_list2.get(groupPosition).get( childPosition));
		   return convertView;
		  }
		 
		  @Override
		  public boolean isChildSelectable(int groupPosition, int childPosition) {
		   return true;
		  }
		 
		 }
class SavedBranchListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	public SavedBranchListAdapter(Context context) {
		
					
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}
	
	
	final class Zujian{  
	    public TextView product,branch,num,money,increase,decrease;  
      
    
   }   //end of Zujian

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		 return Saved_Branch_JA.size();  
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return Saved_Branch_JA.getJSONObject(position);  
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}
 
	@Override
	public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_branchsaved_act_shop, null);  
	            zj.product=(TextView) convertView.findViewById(R.id.tv_productname_list_branchsaved_act_shop);
	            zj.branch=(TextView) convertView.findViewById(R.id.tv_branchname_list_branchsaved_act_shop);
	            zj.num=(TextView) convertView.findViewById(R.id.tv_branchnum_list_branchsaved_act_shop);
	            zj.money=(TextView) convertView.findViewById(R.id.tv_branchmoney_list_branchsaved_act_shop);
	            zj.increase=(TextView) convertView.findViewById(R.id.tv_increase_list_branchsaved_act_shop);
	            zj.decrease=(TextView) convertView.findViewById(R.id.tv_decrease_list_branchsaved_act_shop);
	            convertView.setTag(zj);  
	            System.out.println("position----"+position+"------inflated");
	        }else{   System.out.println("position----"+position+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  		        						  
	        //绑定数据  
	        zj.product.setText(Saved_Branch_JA.getJSONObject(position).getString(OrderProduct.PRODUCTNAME));
	       zj.branch.setText(Saved_Branch_JA.getJSONObject(position).getString(OrderProduct.BRANCHNAME));
	        
	        int Branch_Num=Saved_Branch_JA.getJSONObject(position).getInt(Car.NUMBER);
	        zj.num.setText(String.valueOf(Branch_Num)+"份");
	        
	       double Money=Saved_Branch_JA.getJSONObject(position).getDouble(OrderProduct.BRANCHPRICE)*Branch_Num;
	       zj.money.setText("￥"+String.valueOf(Money));
	        
	        
             zj.decrease.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int number=Saved_Branch_JA.getJSONObject(selectID).getInt(Car.NUMBER);
					if(number>1){
						JSONObject temp= Saved_Branch_JA.getJSONObject(selectID);
						temp.put(Car.NUMBER, temp.getInt(Car.NUMBER)-1);
						 new CarDao(context).updateOneRecord(temp);	
					}else{
						new CarDao(context).deleteOneRecord(Saved_Branch_JA.getJSONObject(selectID));
					}
					refresh_saved();
				  
				}
			});
            zj.increase.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stubcarDao.updateOneRecord(check);
					JSONObject temp= Saved_Branch_JA.getJSONObject(selectID);
					temp.put(Car.NUMBER, temp.getInt(Car.NUMBER)+1);
					 new CarDao(context).updateOneRecord(temp);				 
				    refresh_saved();
				  
				}
			});
	        return convertView;
           } 
      }// end Adapter

private void refresh_saved(){
	// 一家店铺，是可以供应多个时间段的。只是，一个产品，只能有一个目录， 一个目录只有一个时间段。
	Saved_Branch_JA=new CarDao(ShopAct.this).queryBySupplier(carJO);
    
  		/*----刷新ExpandaleList中的数量--ste1 清空原来的数据----*/
  		
		  for(int j=0;j<ja_index_product.size();j++){
			ja_index_product.getJSONObject(j).put("Selected_Num_InIndex", 0);
		    	for(int k=0;k<ja_index_product.getJSONObject(j).getJSONArray("products").size();k++){		
		    		ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).put("Selected_Num_InProduct",0);
		    	}
		    	}
		  /*----刷新ExpandaleList中的数量--ste2累加新数据 ,并给Saved_Branch_JA赋值----*/
		  int num = 0;
		    double money = 0;
  		 for(int i=Saved_Branch_JA.size()-1;i>=0;i--){
  			 int Product_ID=Saved_Branch_JA.getJSONObject(i).getInt(Car.PRODUCT);
  			 int Branch_Num=Saved_Branch_JA.getJSONObject(i).getInt(Car.NUMBER);
  			 int Branch_ID=Saved_Branch_JA.getJSONObject(i).getInt(Car.BRANCH);
  			 int J = 0,K=0;
  			 double branchPrice=-1; String productName=""; String branchName="";
  			 int branchVolume=-1,productType=-1;
  			 String productDir="";
  			    for(int j=0;j<ja_index_product.size();j++)
  			    	for(int k=0;k<ja_index_product.getJSONObject(j).getJSONArray("products").size();k++){
  			    		if(Product_ID==ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getInt(Product.ID)){
  			    		 J=j; K=k;
  			    	     productName=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getString(Product.NAME);
  			    	     productType=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getInt(Product.TYPE);
  			    	     productDir=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getString(Product.DIR);
  			    	   productDir+="0.jpg";
  			    	   for(int q=0;q<ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").size();q++){
			    			   if(Branch_ID==ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getInt(Branch.ID)){
			    				   branchName=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getString(Branch.NAME);
			    			       branchPrice=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getDouble(Branch.PRICE);
			    			       branchVolume=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getInt(Branch.VOLUME);
			    			       break;}
			    		   }		
  			    		}
  			    	}
  			if(branchPrice==-1){
  				 new CarDao(ShopAct.this).deleteOneRecord(Saved_Branch_JA.getJSONObject(i));
  				 Saved_Branch_JA.remove(i);
  			}else{
  				Saved_Branch_JA.getJSONObject(i).put(OrderProduct.BRANCHPRICE,branchPrice);
  				Saved_Branch_JA.getJSONObject(i).put(OrderProduct.PRODUCTNAME,productName);
  				Saved_Branch_JA.getJSONObject(i).put(OrderProduct.BRANCHNAME,branchName);
  				Saved_Branch_JA.getJSONObject(i).put(OrderProduct.BRANCHVOLUME,branchVolume);
  				Saved_Branch_JA.getJSONObject(i).put(OrderProduct.PRODUCTTYPE,productType);
  				Saved_Branch_JA.getJSONObject(i).put(OrderProduct.DIR,productDir);
  				int numexistedInProduct=ja_index_product.getJSONObject(J).getJSONArray("products").getJSONObject(K).getInt("Selected_Num_InProduct");
		    	ja_index_product.getJSONObject(J).getJSONArray("products").getJSONObject(K).put("Selected_Num_InProduct",numexistedInProduct+Branch_Num);
		    		
		    	int numexistedInIndex=ja_index_product.getJSONObject(J).getInt("Selected_Num_InIndex");
		    	ja_index_product.getJSONObject(J).put("Selected_Num_InIndex", numexistedInIndex+Branch_Num);
		    	
		    	num+=Branch_Num;
		    	money+=Branch_Num*branchPrice;
  			}    
  			    
  		 }
  		 
  		  String temp="("+num+"份"+ money+"元)";
    		branch_incar.setText(temp);
    		isBeyongMoneyMini= money>supplierJO.getDouble(Supplier.MONEYMINI);
  		 myListAdapter.notifyDataSetChanged();
  		 savedListAdapter.notifyDataSetChanged();
}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		  if(isShowSaved){
           hide_lt_saved();   
             return true; 
             }else{
            	 ShopAct.this.finish(); 
             }
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		String temp=intent.getStringExtra("Product");
		System.out.println("-----product act 返回----"+temp);
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		refresh_saved();
		super.onResume();
	}
	
}
